<?php
/**
 * Created by PhpStorm.
 * User: zcq
 * Date: 2018/10/16
 * Time: 15:01
 */

namespace app\admin\controller;


use app\admin\service\VoteService;
use app\admin\service\VoteTypeService;
use think\Request;

class VoteType extends Base
{
    public $typeService;
    public $voteService;
    public function __construct(Request $request = null,VoteTypeService $voteTypeService,VoteService $voteService)
    {
        parent::__construct($request);
        $this->typeService = $voteTypeService;
        $this->voteService = $voteService;
    }

    public function index()
    {
        $voteId = input('vote_id/d');
        $vote = $this->check($voteId);
        $data = $this->typeService->getList($voteId);
        $this->assign('vote',$vote);
        $this->assign('data',$data);
        return $this->fetch();
    }

    public function add()
    {
        $params = input();
        $vote = $this->check($params['vote_id']??0);
        if(\request()->isPost()){
            $params['id'] = 0;
            $res = $this->typeService->save($params);

            return dataReturn($res['code'],$res['msg']);
        }
        $this->assign('vote',$vote);
        $this->assign('url',url('add'));
        $this->assign('data',1);
        $this->assign('title','新增分类');
        return $this->fetch('info');
    }

    public function update()
    {
        $params = input();
        $id = input('id/d');
        $data = $this->typeService->find($id);
        $vote = $this->check($data['vote_id']);

        if(\request()->isPost()){
            $res = $this->typeService->save($params);
            return dataReturn($res['code'],$res['msg']);
        }
        $data->head_img = $data->head_img?:'';
        $this->assign('vote',$vote);
        $this->assign('url',url('update'));
        $this->assign('data',json_encode($data));
        $this->assign('title','编辑分类');
        return $this->fetch('info');
    }


    public function ajaxUpdate()
    {
        $params = input();
        $res = $this->typeService->updateByField($params);
        return dataReturn($res['code'],$res['msg']);
    }

    public function check($voteId)
    {
        $vote = $this->voteService->check($voteId);
        if(!$vote)
            $this->error('不存在');
        return $vote;
    }
}